import React, { useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import Tables from '@/hoc/Tables';
import Models from '@/components/Models';
import { regPhone } from '@/utils/regular';
import { checkMobile } from '@/services/login';
import { disableUser, insertUser, updateUser } from '@/services/regime';
import { userData } from './index.d';
import styles from './index.less';
import { getAuthorityUser } from '@/utils/authority';
import { REDGIME_LIST } from '@/services/list';
import AddressSelect from '@/components/AddressSelect';
import { setAddressList, setAddressValue } from '@/utils/utils';
import { GenericProps, TableProps } from '@/global.d';
const { Option } = Select;

const Regime: React.FC<GenericProps> = props => {
  const childRef = useRef<TableProps | any>();
  let title = props?.route?.name;
  let columns: any[] = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '单位',
      dataIndex: 'company',
      key: 'company',
    },
    {
      title: '用户组',
      dataIndex: 'userGroup',
      key: 'userGroup',
      render: (_: any, text: any) => (
        <>
          <span style={{ color: '#F65401' }}>{getAuthorityUser(text?.userGroup)}</span>
        </>
      ),
    },
    {
      title: '作品',
      dataIndex: '1',
      key: '1',
    },
    // {
    //   title: '投稿',
    //   dataIndex: '2',
    //   key: '2',
    // },
    // {
    //   title: '入围',
    //   dataIndex: '3',
    //   key: '3',
    // },
    {
      title: '操作',
      width: 250,
      render: (item: any) => (
        <div className="operation">
          <span>查看</span>
          <span
            onClick={() => {
              onEdit(item);
            }}>
            修改
          </span>
          <span
            onClick={() => {
              onisDis(item, !item?.state ? 1 : 0);
            }}>
            {item?.state ? '启用' : '停用'}
          </span>
        </div>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [itemObj, setItemObj] = useState<any>({});

  /**
   * 添加用户
   */
  const onChange = () => {
    setVisible(true);
  };

  /**
   * 弹窗关闭
   */
  const handleCancel = () => {
    setVisible(false);
    setItemObj({});
    form.resetFields();
  };

  /**
   * 提交
   * @param values
   */
  const onFinish = (values: userData) => {
    let value: any = { ...values, id: itemObj?.id, ...setAddressValue(values.code1) };

    if (!itemObj?.id) {
      checkMobile(value).then((res: any) => {
        if (res?.responseCode == 200 && !res?.data) {
          insertUser(value).then(resp => {
            if (resp?.responseCode == 200) {
              message.success('保存成功');
              handleCancel();
              childRef.current.setQuery({});
            } else {
              message.error('保存失败');
            }
          });
        } else {
          form.setFields([
            {
              name: 'mobile',
              value: values?.mobile,
              errors: ['手机号码存在！'],
            },
          ]);
        }
      });
    } else {
      updateUser(value).then(resp => {
        if (resp?.responseCode == 200) {
          message.success('编辑成功');
          handleCancel();
          childRef.current.setQuery({});
        } else {
          message.error('编辑失败');
        }
      });
    }
  };

  /**
   * 编辑
   * @param item
   */
  const onEdit = (item: any) => {
    setItemObj(item);
    form.setFieldsValue({
      ...item,
      code1: setAddressList(item),
    });
    onChange();
  };

  /**
   * 禁用
   */
  const onisDis = (item: any, id: number) => {
    Modal.confirm({
      title: `${item?.state ? '启用' : '停用'}提示`,
      content: `确定要${item?.state ? '启用' : '停用'}${item?.userName}用户吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        disableUser({ id: item.id, type: id }).then(res => {
          if (res?.responseCode == 200 && res?.data) {
            message.success('状态更改成功');
            childRef.current.setQuery({});
          } else {
            message.error('状态修改失败');
          }
        });
      },
    });
  };

  return (
    <div className={styles.regimePage}>
      <PageTitle
        title={title}
        right={
          <Button className="btn_red" onClick={onChange}>
            添加
          </Button>
        }
      />
      <div className="regime_table">
        <Tables childRef={childRef} url={REDGIME_LIST} columns={columns} />
      </div>
      <Models className="add_regime" width="540px" visible={visible} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} name="control-hooks" onFinish={onFinish}>
          <div className="add_user">{itemObj?.id ? '修改用户信息' : '新增用户'}</div>
          <div className="hr"></div>
          <div className="add_user_form" style={{ width: 420 }}>
            <Form.Item
              label="手机号码"
              name="mobile"
              required={false}
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: regPhone(), message: '请输入正确的手机号码' },
              ]}>
              <Input size="large" className="regime_input" allowClear placeholder="请输入手机号码" />
            </Form.Item>
            <Form.Item label="用户姓名" name="userName" required={false} rules={[{ required: true, message: '请输入用户姓名' }]}>
              <Input size="large" className="regime_input" allowClear placeholder="请输入用户姓名" />
            </Form.Item>
            <Form.Item label="所属单位" name="company" required={false} rules={[{ required: true, message: '请输入所属单位' }]}>
              <Input size="large" className="regime_inputs" allowClear placeholder="请输入所属单位" />
            </Form.Item>
            <Form.Item label="所在省市" name="code1" required={false} rules={[{ required: true, message: '请选择所在省市' }]}>
              <AddressSelect width={100} size="large" />
            </Form.Item>
            <Form.Item label=" " colon={false} name="address" required={false}>
              <Input size="large" className="regime_inputs" allowClear placeholder="请输入详细地址" />
            </Form.Item>
            <Form.Item label="用户组" name="userGroup" required={false} rules={[{ required: true, message: '请选择用户组' }]}>
              <Select size="large" className="regime_input" placeholder="请选择用户组" allowClear>
                <Option value="1">管理员</Option>
                <Option value="2">作者</Option>
                <Option value="3">评审老师</Option>
                <Option value="4">审改老师</Option>
                <Option value="5">实体印章管理员</Option>
              </Select>
            </Form.Item>
          </div>
          <div className="hr"></div>
          <div className="regime_btns">
            <Button className="btn_cold" onClick={handleCancel}>
              取消
            </Button>
            <Button className="btn_red" htmlType="submit">
              提交
            </Button>
          </div>
        </Form>
      </Models>
    </div>
  );
};

export default Regime;
